﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using StockCrawlerLib.DAL;
using DevExpress.Web;
using DevExpress.Data;
using CrawlerController;
using StockCrawlerLib;
using StockCrawler.UserControl;
using System.Text.RegularExpressions;

namespace StockCrawler.UserControl
{
    public partial class StockFilterTest : System.Web.UI.Page
    {
        private StockRepository _stockRepo = new StockRepository();
        private HistoryRepository _hisRepo = new HistoryRepository();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                cboSelect.SelectedIndex = 5;
                lblNumDaysBefore.Text = "Số ngày giảm liên tục";
                cboNumDaysBefore.SelectedIndex = 2;
                lblNumDaysAfter.Text = "Sau khi tăng liên tục";
                cboNumDaysAfter.SelectedIndex = 0;
                cboChangedRange.SelectedIndex = 0;
                cboVolumnRange.SelectedIndex = 0;
                InitMasterGrid2();
            }
        }

        private void InitMasterGrid2()
        {
            if (cboSelect.SelectedIndex == 0) //All
            {
                chkIncludeNoneChangeBefore.Enabled = false;
                chkIncludeNoneChangeAfter.Enabled = false;
            }
            else
            {
                chkIncludeNoneChangeBefore.Enabled = true;
                chkIncludeNoneChangeAfter.Enabled = true;
            }
            
            gridViewHistory.DataSource = null;
            gridViewHistory.DataBind();

            gridViewStock.DataSource = null;
            if (cboSelect.SelectedIndex == 0) //All
            {
                gridViewStock.DataSource = _stockRepo.GetDefaultStockList();
            }
            else if (cboSelect.SelectedIndex == 1) //Remark
            {
                gridViewStock.DataSource = _stockRepo.GetRemarkStockList();
            }
            else if (cboSelect.SelectedIndex == 6) //New Stocks
            {
                lblNumDaysBefore.Text = "Số ngày lên sàn ";
                int numDaysBefore = int.Parse(cboNumDaysBefore.SelectedItem.Value.ToString());
                gridViewStock.DataSource = _stockRepo.GetNewStockList(numDaysBefore);
            }
            else if (cboSelect.SelectedIndex == 7) //Khối lượng tăng đột biến
            {
                lblNumDaysBefore.Text = "KL tăng đột biến";
                int numDaysBefore = int.Parse(cboNumDaysBefore.SelectedItem.Value.ToString());
                int volumeRange = int.Parse(cboVolumnRange.SelectedItem.Value.ToString());
                int volumeTimes = int.Parse(cboTimes.SelectedItem.Value.ToString());
                gridViewStock.DataSource = _hisRepo.SelectKLDotBien(numDaysBefore, volumeRange, volumeTimes, true);
            }
            else if (cboSelect.SelectedIndex == 8) //Khối lượng giảm đột biến
            {
                lblNumDaysBefore.Text = "KL giảm đột biến";
                int numDaysBefore = int.Parse(cboNumDaysBefore.SelectedItem.Value.ToString());
                int volumeRange = int.Parse(cboVolumnRange.SelectedItem.Value.ToString());
                int volumeTimes = int.Parse(cboTimes.SelectedItem.Value.ToString());
                gridViewStock.DataSource = _hisRepo.SelectKLDotBien(numDaysBefore, volumeRange, volumeTimes, false);
            }
            else
            {
                string changedRange = cboChangedRange.SelectedItem.Value.ToString();
                int volumeRange = int.Parse(cboVolumnRange.SelectedItem.Value.ToString());
                int numDaysBefore = int.Parse(cboNumDaysBefore.SelectedItem.Value.ToString());
                int numDaysAfter = int.Parse(cboNumDaysAfter.SelectedItem.Value.ToString());

                bool isIncludeNoneChangeBefore = false;
                if (chkIncludeNoneChangeBefore.Checked)
                    isIncludeNoneChangeBefore = true;

                bool isIncludeNoneChangeAfter = false;
                if (chkIncludeNoneChangeAfter.Checked)
                    isIncludeNoneChangeAfter = true;

                if (cboSelect.SelectedIndex == 2) //CE
                {
                    lblNumDaysBefore.Text = "Số ngày tăng trần liên tục";
                    lblNumDaysAfter.Text = "Sau khi giảm sàn liên tục";
                    cboNumDaysBefore.SelectedIndex = 0;
                    gridViewStock.DataSource = _hisRepo.SelectCEFLFilter(true, numDaysAfter, numDaysBefore, changedRange, volumeRange);
                }
                else if (cboSelect.SelectedIndex == 3) //FL
                {
                    lblNumDaysBefore.Text = "Số ngày giảm sàn liên tục";
                    lblNumDaysAfter.Text = "Sau khi tăng trần liên tục";
                    cboNumDaysBefore.SelectedIndex = 0;
                    gridViewStock.DataSource = _hisRepo.SelectCEFLFilter(false, numDaysAfter, numDaysBefore, changedRange, volumeRange);
                }
                else if (cboSelect.SelectedIndex == 4) //Increase
                {
                    lblNumDaysBefore.Text = "Số ngày tăng liên tục";
                    lblNumDaysAfter.Text = "Sau khi giảm liên tục";
                    gridViewStock.DataSource = _hisRepo.SelectByFilter2(true, numDaysAfter, isIncludeNoneChangeAfter, numDaysBefore, isIncludeNoneChangeBefore, changedRange, volumeRange);
                }
                else if (cboSelect.SelectedIndex == 5) //Decrease
                {
                    lblNumDaysBefore.Text = "Số ngày giảm liên tục";
                    lblNumDaysAfter.Text = "Sau khi tăng liên tục";
                    gridViewStock.DataSource = _hisRepo.SelectByFilter2(false, numDaysAfter, isIncludeNoneChangeAfter, numDaysBefore, isIncludeNoneChangeBefore, changedRange, volumeRange);
                }
                
            }
            gridViewStock.PageIndex = 0;
            gridViewStock.DataBind();
        }

        protected void gridViewHistory_HtmlDataCellPrepared(object sender, ASPxGridViewTableDataCellEventArgs e)
        {
            try
            {
                if (e.DataColumn.FieldName == "thay_doi")
                {
                    float gia_dong_cua = (float)gridViewHistory.GetRowValues(e.VisibleIndex, new string[] { "gia_dong_cua" });
                    float thay_doi = (float)gridViewHistory.GetRowValues(e.VisibleIndex, new string[] { "thay_doi" });
                    float gia_tran = (float)gridViewHistory.GetRowValues(e.VisibleIndex, new string[] { "gia_tran" });
                    float gia_san = (float)gridViewHistory.GetRowValues(e.VisibleIndex, new string[] { "gia_san" });
                    if (thay_doi < 0)
                    {
                        if (gia_dong_cua == gia_san)
                            e.Cell.ForeColor = System.Drawing.Color.FromArgb(0x66, 0xCC, 0xFF);
                        else
                            e.Cell.ForeColor = System.Drawing.Color.FromArgb(0xFF, 0x00, 0x00);
                    }
                    else if (thay_doi > 0)
                        if (gia_dong_cua == gia_tran)
                            e.Cell.ForeColor = System.Drawing.Color.FromArgb(0xFF, 0x00, 0xFF);
                        else
                            e.Cell.ForeColor = System.Drawing.Color.FromArgb(0x00, 0xFF, 0x00);
                    else
                    {
                        e.Cell.ForeColor = System.Drawing.Color.FromArgb(0xF7, 0xFF, 0x31);
                    }
                }
                else if (e.DataColumn.FieldName == "gia_dong_cua" || e.DataColumn.FieldName == "gia_mo_cua"
                    || e.DataColumn.FieldName == "gia_cao_nhat" || e.DataColumn.FieldName == "gia_thap_nhat")
                {
                    float gia_tham_chieu = (float)gridViewHistory.GetRowValues(e.VisibleIndex, new string[] { "gia_tham_chieu" });
                    float gia_tran = (float)gridViewHistory.GetRowValues(e.VisibleIndex, new string[] { "gia_tran" });
                    float gia_san = (float)gridViewHistory.GetRowValues(e.VisibleIndex, new string[] { "gia_san" });

                    float value = (float)e.CellValue;
                    if (value == gia_san)
                        e.Cell.ForeColor = System.Drawing.Color.FromArgb(0x66, 0xCC, 0xFF);
                    else if (value == gia_tran)
                        e.Cell.ForeColor = System.Drawing.Color.FromArgb(0xFF, 0x00, 0xFF);
                    else if (value < gia_tham_chieu)
                        e.Cell.ForeColor = System.Drawing.Color.FromArgb(0xFF, 0x00, 0x00);
                    else if (value > gia_tham_chieu)
                        e.Cell.ForeColor = System.Drawing.Color.FromArgb(0x00, 0xFF, 0x00);
                    else
                        e.Cell.ForeColor = System.Drawing.Color.FromArgb(0xF7, 0xFF, 0x31);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            
        }

        protected void cboNumDaysBefore_SelectedIndexChanged(object sender, EventArgs e)
        {
            InitMasterGrid2();
        }

        protected void cboVolumnRange_SelectedIndexChanged(object sender, EventArgs e)
        {
            InitMasterGrid2();
        }

        protected void cboChangedRange_SelectedIndexChanged(object sender, EventArgs e)
        {
            InitMasterGrid2();
        }

        protected void cboNumDaysAfter_SelectedIndexChanged(object sender, EventArgs e)
        {
            InitMasterGrid2();
        }

        protected void chkIncludeNoneChangeBefore_CheckedChanged(object sender, EventArgs e)
        {
            InitMasterGrid2();
        }

        protected void chkIncludeNoneChangeAfter_CheckedChanged(object sender, EventArgs e)
        {
            InitMasterGrid2();
        }

        protected void chkIsRemark_CheckedChanged(object sender, EventArgs e)
        {
            ASPxCheckBox chk = (ASPxCheckBox)sender;
            //"cell4_1"
            Regex r = new Regex("cell(?<value>[0-9]+)_[0-9]+");
            Match m = r.Match(chk.Parent.ID);
            int rowIndex = int.Parse(m.Result("${value}"));

            int id_stock = (int)gridViewStock.GetRowValues(rowIndex, new string[] { "id_stock" });
            if (id_stock > 0)
            {
                Session["id_stock"] = id_stock;
                string code = _stockRepo.Select(id_stock).code;
                _stockRepo.UpdateIsRemark(id_stock, chk.Checked);
            }
        }

        protected void ASPxCallbackStock_Callback(object sender, DevExpress.Web.CallbackEventArgsBase e)
        {
            InitMasterGrid2();
        }

        protected void ASPxCallback1_Callback(object sender, DevExpress.Web.CallbackEventArgsBase e)
        {
            try
            {
                string[] args = e.Parameter.Split('|');
                if (args == null || args.Length == 0)
                    return;
                
                gridViewHistory.DataSource = null;
                if (gridViewStock.VisibleRowCount > 0)
                {
                    if (args[0].Equals("INDEX"))
                    {
                        int id_stock = (int)gridViewStock.GetRowValues(Convert.ToInt32(args[1]), new string[] { "id_stock" });
                        Session["id_stock"] = id_stock;

                        CafefCrawler cafef = new CafefCrawler();
                        string code = gridViewStock.GetRowValues(Convert.ToInt32(args[1]), new string[] { "code" }).ToString();
                        pricebox.Controls.AddAt(0, new LiteralControl(cafef.GetCurrentInfo(code)));

                        //FptsCrawler cafef = new FptsCrawler();
                        //string code = gridViewStock.GetRowValues(Convert.ToInt32(args[1]), new string[] { "code" }).ToString();
                        //stock obj = _stockRepo.Select(code);
                        //e.Result = cafef.GetCurrentInfo(obj.id_fpt.ToString());

                        var dt = _hisRepo.Select2(id_stock);
                        gridViewHistory.DataSource = dt;
                        gridViewHistory.DataBind();
                    }
                    else if (args[0].Equals("SORT"))
                    {
                        int id_stock = (int)Session["id_stock"];

                        var dt = _hisRepo.Select2(id_stock);
                        gridViewHistory.DataSource = dt;
                        gridViewHistory.DataBind();
                        if (args[1] == "ngay_giao_dich")
                        {
                            ColumnSortOrder order = args[2] == "ASC" ? ColumnSortOrder.Ascending : ColumnSortOrder.Descending;
                            gridViewHistory.SortBy(gridViewHistory.Columns[args[1]], order);
                        }
                    }
                    //else if (args[0].Equals("PAGING"))
                    //{
                    //    int id_stock = (int)gridViewStock.GetRowValues(gridViewStock.VisibleStartIndex, new string[] { "id_stock" });
                    //    Session["id_stock"] = id_stock;

                    //    var dt = _hisRepo.Select2(id_stock);
                    //    gridViewHistory.DataSource = dt;
                    //    gridViewHistory.DataBind();
                    //}
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        protected void cboSelect_SelectedIndexChanged(object sender, EventArgs e)
        {
            InitMasterGrid2();
        }

    }
}